﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Extented.UI.Core.Helpers
{
    public static class HttpContextAccessor
    {
        static readonly PropertyInfo property;
        public static object Current
        {
            get
            {
                try
                {
                    return property != null ? property.GetValue(null, new object[0]) : null;
                }
                catch
                {
                    return null;
                }
            }
        }
        public static object Server
        {
            get { return GetPropertyValue(Current, "Server"); }
        }
        public static object Request
        {
            get { return GetPropertyValue(Current, "Request"); }
        }
        public static Uri Url
        {
            get { return (Uri)GetPropertyValue(Request, "Url"); }
        }
        static object GetPropertyValue(object obj, string name)
        {
            if (obj != null)
            {
                PropertyInfo property = obj.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public);
                return property.GetValue(obj, new object[0]);
            }
            return null;
        }
        static HttpContextAccessor()
        {
            if (SystemWebAssemblyLoader.SystemWeb == null)
                return;
            try
            {
                Type type = SystemWebAssemblyLoader.SystemWeb.GetType("System.Web.HttpContext");
                property = type.GetProperty("Current", BindingFlags.Static | BindingFlags.Public);
            }
            catch
            {
            }
        }
    }
}
